//
//  IGGamesViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGGamesViewController.h"
#import "IG_GameGroupViewController.h"
#import "IG_GameTopGroupTableViewCell.h"
#import "IG_GameDateCollectionViewCell.h"
#import "IG_GameTodayTableViewCell.h"
#import "IG_GameHotTableViewCell.h"
#import "IG_GameNoneTableViewCell.h"
#import "IGLivePlayer.h"
#import "IG_RoundDetailViewController.h"
#import "IGCustomNavigationController.h"
#import "IG_GameBigGamesViewController.h"
#import "IG_GameGamesViewController.h"
@interface IGGamesViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong)IG_GameGroupViewController *groupVC;
@property (nonatomic, strong)AppDelegate *appdelegate;
@property (nonatomic, strong) UIActivityIndicatorView *flower;
@property (nonatomic, strong) IGLivePlayer *player;
@property (nonatomic, strong) UIButton *button;
@end

@implementation IGGamesViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    IGCustomNavigationController *navC = (IGCustomNavigationController *)self.navigationController;
    navC.groupButton.hidden = NO;
    navC.downImage.hidden = NO;
    navC.label.hidden = YES;
    [navC.groupButton addTarget:self action:@selector(groupButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [navC.downImage addTarget:self action:@selector(groupButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _requestStart = 0;
        IGRightTabBarController *tabBarController = (IGRightTabBarController *)self.navigationController.parentViewController;
        tabBarController.tabBar.hidden = NO;
        navC.iconButton.hidden = NO;
        navC.backButton.hidden = YES;
}



- (void)groupButtonClick:(UIButton *)sender {
    CGRect frame = _groupVC.view.frame;
    IGCustomNavigationController *navC = (IGCustomNavigationController *)self.navigationController;
    if (frame.size.height == 0) {
        frame.size.height = (kScreenHeight - 113) / 3 + 20;
        navC.image.hidden = NO;
    } else {
            frame.size.height = 0;
        navC.image.hidden = YES;
    }
    [UIView animateWithDuration:0.1 animations:^{
        _groupVC.view.frame = frame;        
    }];
    
}



- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    _groupVC.view.frame = CGRectMake((kScreenWidth - 200) / 2, 64, 200, 0);
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_selectIndex < _todayIndex ) {
            _requestStart += 10;
            _isRefresh = YES;
            [self setUpHotGameDataWithDate:_selectDate];
        } else {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestStart = 0;
        _isRefresh = YES;
        [self setUpHotGameDataWithDate:_selectDate];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _appdelegate = [UIApplication sharedApplication].delegate;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.autoresizesSubviews = NO;
    _uid = 0;
    _isRefresh = NO;
    _groupVC.tableView.separatorInset = UIEdgeInsetsZero;
    _hotGameDataArray = [NSMutableArray array];
    _groupVC = [[IG_GameGroupViewController alloc] initWithNibName:@"IG_GameGroupViewController" bundle:nil];
    _groupVC.view.backgroundColor = [UIColor clearColor];
    _groupVC.view.frame = CGRectMake((kScreenWidth - 200) / 2, 64, 200, 0);
    [self.view addSubview:_groupVC.view];
    _groupVC.tableView.delegate = self;
    _groupVC.tableView.dataSource = self;
    _groupVC.tableView.tag = 100;
    _tableView.tag = 101;
    [_tableView registerNib:[UINib nibWithNibName:@"IG_GameTodayTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_GameTodayTableViewCell"];
    [_groupVC.tableView registerNib:[UINib nibWithNibName:@"IG_GameTopGroupTableViewCell" bundle:nil] forCellReuseIdentifier:@"GroupCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IG_GameHotTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_GameHotTableViewCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IG_GameNoneTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_GameNoneTableViewCell"];
    //  collectionView
    [self setUpCollectionViewData];
    _collectionView.autoresizesSubviews = NO;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.itemSize = CGSizeMake(kScreenWidth / 8 , 80);
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    [_collectionView setCollectionViewLayout:layout];
    [_collectionView registerNib:[UINib nibWithNibName:@"IG_GameDateCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"DateCell"];

}

//  collectionView的数据请求

- (void)setUpCollectionViewData {
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getTournamentDateLine" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSDictionary *allDic = dataDic[@"data"];
        NSArray *beforeArray = allDic[@"before_today"];
        _todayIndex = beforeArray.count;
        _selectIndex = _todayIndex;
        _collectionDataArray = [NSMutableArray array];
        for (int i = 0; i < beforeArray.count; i++) {
            NSDictionary *dic = beforeArray[beforeArray.count - i - 1];
            IG_GameDataModel *model = [[IG_GameDataModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_collectionDataArray addObject:model];
        }
        
        NSDictionary *todayDic = allDic[@"today"];
        _todayModel = [[IG_GameDataModel alloc] init];
        [_todayModel setValuesForKeysWithDictionary:todayDic];
        [_collectionDataArray addObject:_todayModel];
        _selectDate = _todayModel.dateStr;
        NSArray *afterArray = allDic[@"after_today"];
        for (NSDictionary *dic in afterArray) {
            IG_GameDataModel *model = [[IG_GameDataModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_collectionDataArray addObject:model];
        }
        if (_todayIndex > 6 && _todayIndex < 39) {
            [_collectionView setContentOffset:CGPointMake((kScreenWidth / 8 + 5) * (_todayIndex - 3), 0)];
        }
        [_collectionView reloadData];
        [self setUpTodayGamesDataWithDateStr:_todayModel.dateStr];
        [self setUpHotGameDataWithDate:_todayModel.dateStr];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  tableView的数据请求
- (void)setUpTodayGamesDataWithDateStr:(NSString *)dateStr {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getTournamentByDate?date=%@",dateStr];
    parDic[@"sub_list"] = @"5%2C6%2C32%2C7%2C8";
    [IGAFNetworking requestWithUrlString:newUrl parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
            _todayGamesArray = [NSMutableArray array];
        if ([dataDic[@"code"] isEqualToString:@"400"]) {
            return ;
        } else {
            for (NSDictionary *dic in array) {
                IG_GameTodayGamesModel *model = [[IG_GameTodayGamesModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_todayGamesArray addObject:model];
            } 
            [_tableView reloadData];
        }
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  hotGame数据请求
- (void)setUpHotGameDataWithDate:(NSString *)dateStr {
    if (_requestStart == 0) {
        [_hotGameDataArray removeAllObjects];
        
    }
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getHotMatchByDate?date=%@",dateStr];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    parDic[@"num"] = @"10";
    parDic[@"sub_list"] = @"5%2C6%2C32%2C7%2C8";
    parDic[@"uid"] = [NSString stringWithFormat:@"%ld",_uid];
    [IGAFNetworking requestWithUrlString:newUrl parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
        _code = dataDic[@"code"];
        if ([_code isEqualToString:@"200"]) {
            for (NSDictionary *dic in array) {
                IG_GameHotModel *model = [[IG_GameHotModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_hotGameDataArray addObject:model];
            }
            _tableView.tableHeaderView = nil;
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];

        } else if([_code isEqualToString:@"400"]) {
            if (_isRefresh == YES) {
                
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self addLabelToHeadView];
                _todayGamesArray = nil;
                _hotGameDataArray = nil;
                _todayGamesArray = [NSMutableArray array];
                _hotGameDataArray = [NSMutableArray array];
                [_tableView reloadData];
            }
        }
        
        _isRefresh = NO;
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  添加一个暂无数据的label为tableView的表头
- (void)addLabelToHeadView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    label.text = @"暂无数据";
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = label;
}

//  直播数据请求
- (void)setUpLiveDataWithcate:(NSString *)date {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"ios"] = @"1";
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/LiveSourceUrl?cate=%@",date];
    [IGAFNetworking requestWithUrlString:newUrl parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSDictionary *dic = dataDic[@"data"];
        NSString *liveUrl = dic[@"HD"];
        _player = [[IGLivePlayer alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) URL:[NSURL URLWithString:liveUrl]];
        [_appdelegate.window addSubview:_player];
        [self setPlaySubviews];
        [_player addObserver:self forKeyPath:@"vlcPlayer.state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    } error:^(NSError *requestError) {
        NSLog(@"数据请求失败");
    }];
}

#pragma mark -- 播放器设置
//  添加播放器上的子视图
- (void)setPlaySubviews {
    _button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _button.frame = CGRectMake(20, 80, 30, 30);
    [_button setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_appdelegate.window addSubview:_button];
    [self setScreen];

    _flower = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _flower.frame = CGRectMake((kScreenWidth - 25) / 2, (kScreenHeight - 25) / 2, 25, 25);
    [_appdelegate.window addSubview:_flower];
    [_flower startAnimating];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([change[@"new"] integerValue] == VLCMediaPlayerStatePlaying) {
        [_flower stopAnimating];
        
    }
}

- (void)buttonClick:(UIButton *)sender {
    [_player removeObserver:self forKeyPath:@"vlcPlayer.state" context:nil];
    [_player.vlcPlayer stop];
    [_player removeFromSuperview];
    [_button removeFromSuperview];
    [_flower removeFromSuperview];
}

//  设置全屏
- (void)setScreen {
    _button.frame = CGRectMake(kScreenWidth - 60, 40, 30, 30);
    [UIView animateWithDuration:0.1 animations:^{
        _player.frame = CGRectMake(0, 0, kScreenHeight, kScreenWidth);
        _player.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
        
    } completion:^(BOOL finished) {
        _player.transform = CGAffineTransformRotate( _player.transform, M_PI_2);
        _button.transform = CGAffineTransformRotate(_button.transform, M_PI_2);
    }];
}
#pragma mark -- groupVC的tableView协议方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView.tag == 101) {
        return 2;
    } else {
        return 1;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 101) {
        if (section == 0) {
            return nil;
        } else {
            if (_hotGameDataArray.count == 0) {
                return nil;
            } else {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
                label.text = @"热门比赛";
                label.textColor = [UIColor blueColor];
                label.textAlignment = NSTextAlignmentCenter;
                label.backgroundColor = [UIColor clearColor];
                return label;
            }
        }
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 100) {
        return 0;
    } else {
        if (section == 0) {
            return 0;
        } else {
        return 40;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 100) {
        return 5;
    } else {
            if (section == 0) {
                return _todayGamesArray.count;
            } else {
                return _hotGameDataArray.count;
            }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        _gameNameArray = @[@"DOTA2",@"炉石传说",@"CSGO",@"英雄联盟",@"风暴英雄"];
        IG_GameTopGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupCell" forIndexPath:indexPath];
        cell.nameLabel.text = _gameNameArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        if (indexPath.section == 0) {
                IG_GameTodayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_GameTodayTableViewCell" forIndexPath:indexPath];
                IG_GameTodayGamesModel *model = _todayGamesArray[indexPath.row];
                cell.model = model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            } else {
            IG_GameHotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_GameHotTableViewCell"];
            IG_GameHotModel *model = [[IG_GameHotModel alloc] init];
            if (_hotGameDataArray.count != 0) {
                model = _hotGameDataArray[indexPath.row];
            }
            NSString *state = [NSString stringWithFormat:@"%@",model.match_state];
            if ([state isEqualToString:@"2"]) {
                cell.gameStateLabel.textColor = [UIColor redColor];
                cell.goImage.hidden = NO;
            } else {
                if ([state isEqualToString:@"4"]) {
                    cell.goImage.hidden = NO;
                } else {
                    cell.goImage.hidden = YES;
                }
                cell.gameStateLabel.textColor = [UIColor blueColor];
            }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.model = model;
                return cell;
            }
            
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
    return ((kScreenHeight - 113) / 3 + 20) / 5;
    } else {
        if (indexPath.section == 0) {
             return 40;
        } else {
            return 100;
        }
       
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 101) {
        if (indexPath.section == 1) {
            if (_hotGameDataArray.count != 0) {
                IG_GameHotModel *model = _hotGameDataArray[indexPath.row];
                NSString *str = [NSString stringWithFormat:@"%@",model.match_state];
                NSInteger state = [str integerValue];
                if (state == 2) {
                    [self setUpLiveDataWithcate:[NSString stringWithFormat:@"%@",model.cate]];
                } if (state ==  4) {
                    IG_RoundDetailViewController *detailVC = [[IG_RoundDetailViewController alloc] init];
                    detailVC.vid = [NSString stringWithFormat:@"%@",model.vid];
                    [self.navigationController pushViewController:detailVC animated:YES];
                }
            }
        }else {
            IG_GameGamesViewController *gamesVC = [[IG_GameGamesViewController alloc] init];
            IG_GameTodayGamesModel *model = _todayGamesArray[indexPath.row];
            gamesVC.match_stage = model.match_stage;
            gamesVC.tournament_id = [NSString stringWithFormat:@"%@",model.tournament_id];
            gamesVC.name = model.tournament_name;
            [self.navigationController pushViewController:gamesVC animated:YES];
        }
    } else {
        NSArray *idArray = @[@1,@3,@7,@2,@4];
        IG_GameBigGamesViewController *bigVC = [[IG_GameBigGamesViewController alloc] init];
        bigVC.gameID = [idArray[indexPath.row] integerValue];
        bigVC.gameName = _gameNameArray[indexPath.row];
        [self.navigationController pushViewController:bigVC animated:YES];
    }
}

#pragma mark -- collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _collectionDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IG_GameDateCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DateCell" forIndexPath:indexPath];
    cell.dateLabel.layer.cornerRadius = (kScreenWidth / 8) / 2;
    IG_GameDataModel *model = _collectionDataArray[indexPath.row];
    cell.weekLabel.text = model.week;
    cell.weekLabel.adjustsFontSizeToFitWidth = YES;
    NSRange range = {4,2};
    NSString *str1 = [model.dateStr substringWithRange:range];
    NSRange range2 = {6,2};
    NSString *str2 = [model.dateStr substringWithRange:range2];
    if ([model.dateStr isEqualToString:_todayModel.dateStr]) {
        cell.dateLabel.text = @"今天";
        cell.dateLabel.adjustsFontSizeToFitWidth = YES;
        cell.dateLabel.backgroundColor = [UIColor cyanColor];
    } else {
        cell.dateLabel.text = [NSString stringWithFormat:@"%@/%@",str1,str2];
        cell.dateLabel.backgroundColor = [UIColor whiteColor];
        if ([_selectDate isEqualToString:model.dateStr]) {
            cell.dateLabel.alpha = 0.2;
        } else {
            cell.dateLabel.alpha = 1;
        }
    }
   
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_selectIndex != indexPath.row) {
        IG_GameDateCollectionViewCell *cell = (IG_GameDateCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        IG_GameDataModel *model = _collectionDataArray[indexPath.row];
        NSRange range = {4,2};
        NSString *str1 = [model.dateStr substringWithRange:range];
        NSRange range2 = {6,2};
        NSString *str2 = [model.dateStr substringWithRange:range2];
        _selectDate = [NSString stringWithFormat:@"%@/%@",str1,str2];
        cell.dateLabel.alpha = 0.2;
        _selectIndex = indexPath.row;
        _selectDate = model.dateStr;
        _requestStart = 0;
        [self setUpHotGameDataWithDate:model.dateStr];
        [self setUpTodayGamesDataWithDateStr:model.dateStr];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    IG_GameDateCollectionViewCell *cell = (IG_GameDateCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.dateLabel.alpha = 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
